<template>
  <a-form
      :model="ruleForm"
      ref="ruleForm"
      v-bind="layout"
      :rules="rules"
      @finish="handleFinish"
  >

    <a-form-item label="实验名称" name="experiment_name">
      <a-select
        v-model:value="ruleForm.experiment_name"
        style="width: 120px"
        ref="select"
      >
        <a-select-option
          v-for="item in ExperimentNameSelectionOptions"
          :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="样品编号" name="sample_num">
      <a-input v-model:value="ruleForm.sample_num" />
    </a-form-item>
    <a-form-item label="样品名称" name="sample_name">
      <a-input v-model:value="ruleForm.sample_name" />
    </a-form-item>
    <a-form-item label="样品状态" name="sample_status">
      <a-input v-model:value="ruleForm.sample_status" />
    </a-form-item>
    <a-form-item label="样品数量" name="sample_quantity">
      <a-input v-model:value="ruleForm.sample_quantity" />
    </a-form-item>
    <a-form-item label="送样人员" name="delivery_personnel">
      <a-input v-model:value="ruleForm.delivery_personnel" />
    </a-form-item>
    <a-form-item label="检测机构" name="testing_facility">
      <a-input v-model:value="ruleForm.testing_facility" />
    </a-form-item>
    <a-form-item label="委托书编号" name="attorney_number">
      <a-input v-model:value="ruleForm.attorney_number" />
    </a-form-item>
    <a-form-item label="检测编号" name="test_num">
      <a-input v-model:value="ruleForm.test_num" />
    </a-form-item>
    <a-form-item label="送样日期" name="delivery_date">
      <a-date-picker
          placeholder="请选择"
          v-model:value="ruleForm.delivery_date"
          :locale="locale"
      />
      <br />
    </a-form-item>
    <a-form-item label="完成日期" name="finish_date">
      <a-date-picker
          placeholder="请选择"
          v-model:value="ruleForm.finish_date"
          :locale="locale"
      />
      <br />
    </a-form-item>
    <a-form-item label="分析检测报告" name="riddle_report">
      <a-upload
        :fileList="ruleForm.RiddleReportFileList"
        :beforeUpload="beforeRiddleReportUpload"
        :headers="headers"
        @change="handleRiddleReportChange"
      >
        <a-button> <upload-outlined /> 选择 </a-button>
      </a-upload>
    </a-form-item>

    <a-form-item label="主检测设备" name="main_testing_equipment">
      <a-input v-model:value="ruleForm.main_testing_equipment" />
    </a-form-item>
    <a-form-item label="实验金额" name="experiment_amount">
      <a-input v-model:value="ruleForm.experiment_amount" />
    </a-form-item>

    <a-form-item label="附件" name="annex">
      <a-upload
        :fileList="ruleForm.AnnexFileList"
        :beforeUpload="beforeAnnexUpload"
        :headers="headers"
        @change="handleAnnexChange"
      >
        <a-button> <upload-outlined /> 选择 </a-button>
      </a-upload>
    </a-form-item>


    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import moment from 'moment'

export default {
  name: 'AddOrEditAssay',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],
  components: {
    UploadOutlined,
  },
  data() {

    let isValidStr = (str) => {
      return str.indexOf(" ") === -1;
    };
    let validateExperimentName = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择实验名称");
      }
    };
    let validateSampleNum = async (rule, value) => {
      if (value === "") {
        return Promise.reject("输入样品编号");
      }
    };

    let validateSampleName = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请输入样品名称");
      } else {
        if (!isValidStr(value)) {
          return Promise.reject("样品名称含有非法字符");
        }
        return Promise.resolve();
      }
    };

    return {
      ruleForm: {
        experiment_name: '',
        sample_num: '',
        sample_name: '',
        sample_status: '',
        sample_quantity: '',
        delivery_personnel: '',
        testing_facility: '',
        attorney_number: '',
        test_num: '',
        delivery_date:'',
        finish_date: '',
        main_testing_equipment: '',
        experiment_amount: '',
        RiddleReportFileList: [],
        AnnexFileList: [],
      },

      rules: {
        experiment_name:[
          {
            validator: validateExperimentName,
            trigger: "change",
            required: true,
            whitespace: true,
          }
        ],
        sample_num:[
          {
            validator: validateSampleNum,
            trigger: "change",
            required: true,
            whitespace: true,
          }
        ],
        sample_name: [
          {
            validator: validateSampleName,
            trigger: "change",
            required: true,
            whitespace: true,
          },
       ],
      },


      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      locale,
      submitting: false,
      ExperimentNameSelectionOptions: [],
      headers: {
        authorization: 'authorization-text',
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {
      this.ExperimentNameSelectionOptions = []
      this.axios
        .get('/experiment_management/experiment_information/')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; ++i) {
            this.ExperimentNameSelectionOptions.push({
              url: data[i].url,
              label: data[i].experiment_name,
            })
          }
          //this.ruleForm.alloy_code = data.length === 0 ? '' : data[0].url
          if (this.url !== '') {
            this.axios
              .get(this.url)
              .then((res) => {
                const data = res.data
                this.ruleForm.experiment_name = data.experiment_name
                this.ruleForm.sample_num = data.sample_num
                this.ruleForm.sample_name = data.sample_name
                this.ruleForm.sample_status = data.sample_status
                this.ruleForm.sample_quantity = data.sample_quantity
                this.ruleForm.delivery_personnel = data.delivery_personnel
                this.ruleForm.testing_facility = data.testing_facility
                this.ruleForm.attorney_number = data.attorney_number
                this.ruleForm.test_num = data.test_num
                //送样日期
                this.ruleForm.delivery_date = data.delivery_date
                //完成日期
                this.ruleForm.finish_date = data.finish_date
                this.ruleForm.main_testing_equipment = data.main_testing_equipment
                this.ruleForm.experiment_amount = data.experiment_amount
                //分析检测报告???
                if (data.riddle_report_filename !== '') {
                  // console.log('not null')
                  this.ruleForm.RiddleReportFileList.push({
                    uid: '-1',
                    name: data.riddle_report_filename,
                  })
                }
                //附件???
                if (data.annex_filename !== '') {
                  this.ruleForm.AnnexFileList.push({
                    uid: '-2',
                    name: data.annex_filename,
                  })
                }
              })
              .catch((error) => {
                console.log('Error', error.message)
              })
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
          this.ruleForm.experiment_name = ''
        })
    },
    // onChange(e) {
    //   console.log('radio checked', e.target.value)
    // },
    handleFinish(values) {
      this.submitting = true
      const {
        RiddleReportFileList,
        AnnexFileList,
      } = this.ruleForm
      const formData = new FormData()
      formData.append('experiment_name', this.ruleForm.experiment_name)
      formData.append('sample_num', values.sample_num)
      formData.append('sample_name', values.sample_name)
      formData.append('sample_status', values.sample_status)
      formData.append('sample_quantity', values.sample_quantity)
      formData.append('delivery_personnel', values.delivery_personnel)
      formData.append('testing_facility', values.testing_facility)
      formData.append('attorney_number', values.attorney_number)
      formData.append('test_num', values.test_num)
      if(moment(values.delivery_date, 'YYYY-MM-DDTHH:mm:ss').isValid())
      {
        let delivery_date = moment(values.delivery_date).format('YYYY-MM-DDTHH:mm:ss')
        formData.append('delivery_date', delivery_date)
      }
      if(moment(values.finish_date, 'YYYY-MM-DDTHH:mm:ss').isValid())
      {
        let finish_data = moment(values.finish_date).format('YYYY-MM-DDTHH:mm:ss')
        formData.append('finish_date', finish_data)
      }
      // RiddleReportFileList.forEach((file) => {
      //    formData.append('riddle_report', file.originFileObj)
      // })
      formData.append('main_testing_equipment', values.main_testing_equipment)
      formData.append('experiment_amount', values.experiment_amount)
      // AnnexFileList.forEach((file) => {
      //    formData.append('annex', file.originFileObj)
      // })
      RiddleReportFileList.forEach((file) => {
        // console.log(file.originFileObj)
        // console.log(file)
        // 若选择了文件，那么会有originFileObj属性，这种情况直接上传就可以，
        // 若无originFileObj属性，则说明是在编辑，且没有更改文件，文件列表中只有文件名而无文件实体，
        // 这个时候不传文件参数，让后端保持原文件不变
        if ('originFileObj' in file) {
          formData.append('riddle_report', file.originFileObj)
        }
      })
      AnnexFileList.forEach((file) => {
        // console.log(file.originFileObj)
        if ('originFileObj' in file) {
          formData.append('annex', file.originFileObj)
        }
      })

      if (this.url !== '') {
        if (this.ruleForm.RiddleReportFileList.length === 0) {
          formData.append('riddle_report_empty', true)
        }
        if (this.ruleForm.AnnexFileList.length === 0) {
          formData.append('annex_empty', true)
        }
        this.axios
          .put(this.url, formData)
          .then(() => {
            this.submitting = false
            message.success('修改成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('修改失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      } else {
        this.axios
          .post('/experiment_management/riddle/', formData)
          .then(() => {
            this.submitting = false
            message.success('添加成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('添加失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      }
    },
    beforeRiddleReportUpload(file) {
      this.ruleForm.RiddleReportFileList = [
        ...this.ruleForm.RiddleReportFileList,
        file,
      ]
      return false
    },
    handleRiddleReportChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      fileList = fileList.slice(-1)
      this.ruleForm.RiddleReportFileList = fileList
    },

    beforeAnnexUpload(file) {
      this.ruleForm.AnnexFileList = [
        ...this.ruleForm.AnnexFileList,
        file,
      ]
      return false
    },
    handleAnnexChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      fileList = fileList.slice(-1)
      this.ruleForm.AnnexFileList = fileList
    },

  },
}
</script>
